package com.eshop.logging.service.impl;

import java.io.IOException;
import java.util.Iterator;
import com.eshop.utils.FileUtil;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.lang.Dict;
import com.eshop.utils.ValidationUtil;
import java.io.Serializable;
import com.eshop.logging.aop.log.AppLog;
import java.lang.reflect.Method;
import com.eshop.utils.StringUtils;
import cn.hutool.json.JSONObject;
import org.aspectj.lang.reflect.MethodSignature;
import org.aspectj.lang.ProceedingJoinPoint;
import com.eshop.logging.service.dto.LogSmallDTO;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.logging.service.dto.LogErrorDTO;
import com.eshop.logging.service.dto.LogQueryCriteria;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.List;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Pageable;
import com.eshop.dozer.service.IGenerator;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.logging.service.LogService;
import com.eshop.logging.domain.Log;
import com.eshop.logging.service.mapper.LogMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class LogServiceImpl extends BaseServiceImpl<LogMapper, Log> implements LogService
{
    private final LogMapper logMapper;
    private final IGenerator generator;
    
    public LogServiceImpl(final LogMapper logMapper, final IGenerator generator) {
        this.logMapper = logMapper;
        this.generator = generator;
    }
    
    public Object findAllByPageable(final String nickname, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<Log> page = (PageInfo<Log>)new PageInfo((List)this.logMapper.findAllByPageable(nickname));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public Object queryAll(final LogQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<Log> page = new PageInfo(this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        final String status = "ERROR";
        if (status.equals(criteria.getLogType())) {
            map.put("content", this.generator.convert(page.getList(), LogErrorDTO.class));
            map.put("totalElements", page.getTotal());
        }
        map.put("content", page.getList());
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<Log> queryAll(final LogQueryCriteria criteria) {
        return (this.baseMapper).selectList(QueryHelpPlus.getPredicate(Log.class, criteria));
    }
    
    public Object queryAllByUser(final LogQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<Log> page = (PageInfo<Log>)new PageInfo((List)this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", this.generator.convert(page.getList(), (Class)LogSmallDTO.class));
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void save(String username, final String ip, final ProceedingJoinPoint joinPoint, final Log log, final Long uid) {
        final MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        final Method method = signature.getMethod();
        final com.eshop.logging.aop.log.Log aopLog = method.getAnnotation(com.eshop.logging.aop.log.Log.class);
        final String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        final StringBuilder params = new StringBuilder("{");
        final Object[] argValues = joinPoint.getArgs();
        final String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if (argValues != null) {
            for (int i = 0; i < argValues.length; ++i) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        if (log != null) {
            log.setDescription(aopLog.value());
        }
        log.setType(aopLog.type());
        if (uid != null) {
            log.setUid(uid);
        }
        assert log != null;
        log.setRequestIp(ip);
        final String loginPath = "login";
        if (loginPath.equals(signature.getName())) {
            try {
                assert argValues != null;
                username = new JSONObject(argValues[0]).get("username").toString();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
        log.setMethod(methodName);
        log.setUsername(username);
        log.setParams(params.toString() + " }");
        this.save(log);
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void saveApp(String username, final String ip, final ProceedingJoinPoint joinPoint, final Log log, final Long uid) {
        final MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        final Method method = signature.getMethod();
        final AppLog aopLog = method.getAnnotation(AppLog.class);
        final String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
        final StringBuilder params = new StringBuilder("{");
        final Object[] argValues = joinPoint.getArgs();
        final String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
        if (argValues != null) {
            for (int i = 0; i < argValues.length; ++i) {
                params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
            }
        }
        if (log != null) {
            log.setDescription(aopLog.value());
        }
        log.setType(aopLog.type());
        if (uid != null) {
            log.setUid(uid);
        }
        assert log != null;
        log.setRequestIp(ip);
        final String loginPath = "login";
        if (loginPath.equals(signature.getName())) {
            try {
                assert argValues != null;
                username = new JSONObject(argValues[0]).get("username").toString();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
        log.setMethod(methodName);
        log.setUsername(username);
        log.setParams(params.toString() + " }");
        this.save(log);
    }
    
    public Object findByErrDetail(final Long id) {
        final Log log = (Log)this.getById((Serializable)id);
        ValidationUtil.isNull(log.getId(), "Log", "id", id);
        final byte[] details = log.getExceptionDetail();
        return Dict.create().set("exception", new String(ObjectUtil.isNotNull(details) ? details : "".getBytes()));
    }
    
    public void download(final List<Log> logs, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final Log log : logs) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("用户名", log.getUsername());
            map.put("IP", log.getRequestIp());
            map.put("IP来源", log.getAddress());
            map.put("描述", log.getDescription());
            map.put("浏览器", log.getBrowser());
            map.put("请求耗时/毫秒", log.getTime());
            map.put("异常详情", new String(ObjectUtil.isNotNull(log.getExceptionDetail()) ? log.getExceptionDetail() : "".getBytes()));
            map.put("创建日期", log.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void delAllByError() {
        this.logMapper.deleteByLogType("ERROR");
    }
    
    @Transactional(rollbackFor = { Exception.class })
    public void delAllByInfo() {
        this.logMapper.deleteByLogType("INFO");
    }
}
